package com.htime.intercepter;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.htime.domain.User;
import com.htime.domain.ValidationModel;
import com.htime.util.DateUtil;
import com.htime.util.GsonUtil;
import com.htime.util.StringUtil;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by HTime on 2017/3/5.
 */
@Service
public class ValidationService {

    Gson gson = GsonUtil.createGson();

    //生成token
    public String createToken(User user) {
        Map<String, String> param = new HashMap<String, String>();
        param.put("user", user.getUid().toString());
        param.put("time", new Date().getTime() + "");
        String accessToken = gson.toJson(param);
        return accessToken;
    }

    //验证token
    public Boolean verifyAccessToken(String accessToken, ValidationModel model) {
        Boolean isOk = true;

        Map<String, String> param = gson.fromJson(accessToken, new TypeToken<HashMap<String, String>>() {}.getType());
        if(null == param || null == param.get("user") || null == param.get("time"))
            return false;

        //验证UID
        if(!StringUtil.isNumber(param.get("user").toString()))
            return false;
        Long uid = Long.parseLong(param.get("user"));
        model.setUid(uid);

        //验证时间
        Date time = new Date(Long.parseLong(param.get("time")));
        Integer days = DateUtil.calculateDays(time, new Date());
        //token的有效期为1天
        if(days > 1)
            isOk = false;

        return isOk;
    }

}
